package com.easycoding.framework.exception.handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import com.easycoding.framework.io.StringPrintWriter;

/**
 * @author Think
 * 
 */
public class SpringMVCExceptionHandler extends SimpleMappingExceptionResolver {
	private static final Logger logger = LoggerFactory.getLogger(SpringMVCExceptionHandler.class); 
	
	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception exception) {
		if(logger.isDebugEnabled()){
			logger.debug("CustomExceptionHandler..........................");
			logger.debug("{} is {}", new Object[]{"test","test"});
		}
		ModelAndView mv = super.resolveException(request, response, handler, exception);
		//Map<String, Object> map = new HashMap<String, Object>();
		// 我们还需要一个辅助的类StringPrintWriter，因为ex.printStackTrace参数只有个PrintWriter类型的，java自带的StringWriter
		// 不可用,所以我们需要自己实现一个装饰器的StringPrintWriter。
		StringPrintWriter strintPrintWriter = new StringPrintWriter();
		exception.printStackTrace(strintPrintWriter);
		mv.addObject("exception", exception);
		mv.addObject("exmsg", strintPrintWriter.toString());;//将错误信息传递给view     
		return mv;//new ModelAndView("error", map); // 只能在request作用域中
	}
}
